﻿using DCOWebhook.Models;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using System.Net.Mail;

namespace DCOWebhook.Services
{
    public class SmtpEmailService : IEmailService
    {
        private readonly SmtpSettings _smtpSettings;
        private readonly EmailSettings _emailSettings;

        public SmtpEmailService(IOptions<SmtpSettings> smtpOptions, IOptions<EmailSettings> emailOptions)
        {
            _smtpSettings = smtpOptions.Value;
            _emailSettings = emailOptions.Value;
        }

        public async Task SendEmailAsync(string subject, string body, string recipientEmail)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress(_smtpSettings.FromName, _smtpSettings.FromEmail));
            email.To.Add(MailboxAddress.Parse(recipientEmail));
            email.Subject = subject;

            var builder = new BodyBuilder
            {
                TextBody = body
            };

            email.Body = builder.ToMessageBody();

            using var smtp = new MailKit.Net.Smtp.SmtpClient();
            try
            {
                await smtp.ConnectAsync(_smtpSettings.Host, _smtpSettings.Port, _smtpSettings.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto);
                await smtp.AuthenticateAsync(_smtpSettings.Username, _smtpSettings.Password);
                await smtp.SendAsync(email);
                await smtp.DisconnectAsync(true);
            }
            catch (Exception ex)
            {
                // 记录异常或重新抛出
                throw new InvalidOperationException("邮件发送失败。", ex);
            }
        }
    }
}
